import {
    validate,
    Length,
    IsNumberString
} from 'class-validator'

import { BigNumber } from 'bignumber.js'

import { Wallet } from '@app/wallet'
import { Task, TaskType } from '@app/models/task'
import * as utils from '@app/methods/utils'

class Request {
    @Length(3, 8)
    symbol: string = ''

    @IsNumberString()
    minBalance: string = '0'

    senderAddress?: string
}

/**
 * 向钱包地址发送一笔ETH，用于作为以后转账的手续费
 */
export async function sendFee(wallet: Wallet, params: any, callback: any) {
    const model = utils.makeModel(new Request, params)
    const errors = await validate(model)
    if (errors.length > 0) {
        callback(utils.BadRequest2(errors), undefined)
        return
    }

    const minBalance = new BigNumber(model.minBalance)
    if (minBalance.comparedTo(new BigNumber(0)) <= 0) {
        callback(utils.BadRequest('minBalance must be a positive number'), undefined)
        return
    }

    if (model.senderAddress && !wallet.isLocalAccount(model.senderAddress)) {
        callback(utils.BadRequest('not found sender address'), undefined)
        return
    }

    const token = await wallet.getToken(model.symbol)
    if (!token) {
        callback(utils.InvalidToken, undefined)
        return
    }

    const task = new Task()
    task.type = TaskType.SendFee
    task.params = JSON.stringify({
        symbol: model.symbol,
        minBalance: model.minBalance,
        senderAddress: model.senderAddress
    })
    await task.save()
    callback(undefined, { id: task.id, state: 'queued' })
}
